<template>
  <div class="container">
    <!-- 第一行：信息提示和新增按钮 -->
    <el-row type="flex" justify="space-between" class="topbtn">
      <span class="explain">说明：目前支持学科和关键字条件筛选</span>
      <el-button type="success" class="addbtn" icon="el-icon-edit" @click="$router.push('new')">
        新增试题
      </el-button>
    </el-row>

    <!-- 主要信息筛选区 -->
    <el-form :model="filterList" ref="filterList" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="学科" prop="subjectID">
            <el-select class="selects" v-model="filterList.subjectID">
              <el-option
              v-for="(item, index) in list"
              :key="index"
              :label="item.label"
              :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="6">
          <el-form-item label="二级目录" prop="catalogID">
            <el-select class="selects"
            v-model="filterList.catalogID"
            @focus="getCourseDetails">
              <el-option
              v-for="item in second"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="6">
          <el-form-item label="标签" prop="tags">
            <el-select
            class="selects"
            v-model="filterList.tags"
            @focus="getTags"
            >
              <el-option
              v-for="item in tags"
              :key="item.value"
              :label="item.label"
              :value="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="6">
          <el-form-item label="关键字" prop="keyword">
            <el-input v-model="filterList.keyword"></el-input>
          </el-form-item>
          </el-col>
          <el-col :span="6">
           <el-form-item label="试题类型" prop="questionType">
            <el-select class="selects" v-model="filterList.questionType">
              <el-option
              v-for="(item, index) in type"
              :key="index"
              :label="item"
              :value="index+1"></el-option>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="难度" prop="difficulty">
              <el-select class="selects" v-model="filterList.difficulty">
                <el-option
                v-for="(item, index) in difficulty"
               :key="index"
               :label="item"
               :value="index+1"></el-option>
             </el-select>
           </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="方向" prop="direction">
              <el-select class="selects" v-model="filterList.direction">
                <el-option
                v-for="(item, index) in direction"
                :key="index"
                :label="item"
                :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="录入人">
              <el-select class="selects" v-model="filterList.creatorID">
                <el-option
                v-for="item in user"
                :key="item.id"
                :label="item.username"
                :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="题目备注" prop="remarks">
              <el-input v-model="filterList.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业简称" prop="shortName">
              <el-input v-model="filterList.shortName"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6" class="city">
            <el-form-item label="城市" prop="province">
             <el-select class="selects" v-model="filterList.province" @change="getCity(filterList.province)">
                <el-option
                v-for="(item, index) in province"
                :key="index"
                :label="item"
                :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="city" label-width="4px">
              <el-select class="selects" v-model="filterList.city">
                <el-option
                v-for="(item, index) in city"
                :key="index"
                :label="item"
                :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6" class="bottomBtn">
             <el-button  @click="resetForm">清除</el-button>
             <el-button type="primary" @click="getQuestionsList">搜索</el-button>
          </el-col>
        </el-row>
    </el-form>

    <!-- 提示信息 -->
    <el-alert type="info" show-icon :closable="false">
      <i slot="title">数据一共{{questionsList.length}}条</i>
    </el-alert>

    <!-- 表格内容 -->
    <el-table class="tableList"
      :data="questionsList"
      style="width: 100%">
      <el-table-column
        label="试题编号"
        prop="number"
        min-width="120px"
        >
      </el-table-column>
     <el-table-column
        label="学科"
        prop="subject"
        >
      </el-table-column>
      <el-table-column
        label="目录"
        prop="catalog"
        >
      </el-table-column>
      <el-table-column
        label="题型"
        prop="questionType"
        >
        <template slot-scope="scope">
          {{scope.row.questionType | filterType}}
        </template>
      </el-table-column>
      <el-table-column
        label="题干"
        prop="question"
        min-width="260px"
        >
        <template slot-scope="scope">
          {{scope.row.question | html2Text}}
        </template>
      </el-table-column>
      <el-table-column
        label="录入时间"
        prop="addDate"
        min-width="180px"
        >
        <template slot-scope="scope">
          {{filterTime(scope.row.addDate)}}
        </template>
      </el-table-column>
      <el-table-column
        label="难度"
        prop="difficulty"
        >
        <template slot-scope="scope">
          {{scope.row.difficulty | filterDifficulty}}
        </template>
      </el-table-column>
      <el-table-column
        label="录入人"
        prop="creator"
        >
      </el-table-column>
      <!-- 操作区 -->
      <el-table-column
        label="操作"
        min-width="180px"
        >
        <template slot-scope="{row}">
          <!-- 操作按钮区，加Tooltip 文字提示 -->
          <!-- 预览按钮 -->
        <el-tooltip content="预览" placement="bottom" effect="light">
        <el-button
          type="primary"
          icon="el-icon-view"
          :plain="true"
          circle
          @click="handleShow(row.id)"></el-button></el-tooltip>
          <!-- 修改按钮 -->
        <el-tooltip content="修改" placement="bottom" effect="light">
        <el-button
          type="success" icon="el-icon-edit" circle :plain="true"
          @click="handleEdit(row.id)"></el-button></el-tooltip>
          <!-- 删除按钮 -->
        <el-tooltip content="删除" placement="bottom" effect="light">
        <el-button
          type="danger" icon="el-icon-delete" circle :plain="true"
          @click="handleDelete(row.id)"></el-button></el-tooltip>
          <!-- 加入精选按钮 -->
        <el-tooltip content="加入精选" placement="bottom" effect="light">
        <el-button
          type="warning" icon="el-icon-check" circle :plain="true"
          @click="addChoice(row.id)"></el-button></el-tooltip>
      </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-row type="flex" justify="end">
      <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="page.page"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="5"
      layout="prev, pager, next, sizes, jumper"
      :total="counts">
    </el-pagination>
    </el-row>

    <!-- 预览弹框组件 -->
    <QuestionsPreview :isShow.sync="isShow" :list="previewList"></QuestionsPreview>
  </div>
</template>

<script>
// 导入请求
import { getSubjectList2, getCourseDetails, getTags, getUser } from '@/api/hmmm/subjects'
import { provinces, citys } from '@/api/hmmm/citys'
import { getQuestionsList, getQuestionsId, editQuestions, delQuestions, addChoice } from '@/api/hmmm/questions'
// 导入时间格式化工具
import { parseTime } from '@/utils'
// 导入预览弹框组件
import QuestionsPreview from '../components/questions-preview.vue'
export default {
  name: 'BasicQuestion',
  components: {
    QuestionsPreview
  },
  data () {
    return {
      // 控制弹层
      isShow: false,
      // 表格列表
      questionsList: [],
      // 保存基础题库详情
      previewList: {},
      // 保存学科列表
      list: [],
      // 保存二级科目
      second: [],
      // 保存标签
      tags: [],
      // 试题类型
      type: ['单选', '多选', '简单'],
      // 难度
      difficulty: ['简单', '一般', '困难'],
      // 方向
      direction: ['o2o', '外包服务', '企业服务', '互联网金融', '企业咨询', '互联网', '电子商务', '其他'],
      // 录入人
      user: [],
      // 省份
      province: [],
      // 城市
      city: [],
      // 条数
      counts: 0,
      page: {
        page: 1, // 第几页
        pagesize: 5 // 每页几条
      },
      // 保存表单数据
      filterList: {
        subjectID: '',
        catalogID: '',
        tags: '',
        keyword: '',
        questionType: '',
        difficulty: '',
        direction: '',
        creatorID: '',
        remarks: '',
        shortName: '',
        province: '',
        city: ''
      },
      currentPage4: 4
    }
  },
  created () {
    this.getSubjectList2()
    this.getUser()
    this.getProvince()
    this.handleCurrentChange()
    // this.getQuestionsList()
    // this.getQuestionsList()
  },
  methods: {
    // 获取学科简单列表
    async getSubjectList2 () {
      try {
        const { data } = await getSubjectList2()
        // console.log(data)
        // 保存数据
        this.list = data
      } catch (error) {
        console.log(error)
      }
    },
    // 获取二级目录
    async getCourseDetails () {
      const { data } = await getCourseDetails({
        subjectID: this.filterList.subject
      })
      this.second = data
    },
    // 获取标签
    async getTags () {
      const { data } = await getTags({
        subjectID: this.filterList.subject
      })
      this.tags = data
    },
    // 获取录入人
    async getUser () {
      const { data } = await getUser({
        keyword: this.filterList.keyWords
      })
      this.user = data
    },
    // 获取城市
    getProvince () {
      this.province = provinces()
    },
    getCity (pname) {
      this.city = citys(pname)
    },
    // 点击清除事件
    resetForm () {
      // console.log(this.$refs.filterList)
      // bug: 没有给 el-form-item 加prop属性，清除事件不生效
      this.$refs.filterList.resetFields()
    },
    // 获取基础题库
    async getQuestionsList () {
      const obj = {}
      for (const k in this.filterList) {
        if (this.filterList[k]) {
          obj[k] = this.filterList[k]
        }
      }
      // 发接口,接受满足搜索要求的返回值
      const { data } = await getQuestionsList({
        ...obj
      })
      // console.log(data)
      this.questionsList = data.items
    },
    // 格式化时间
    filterTime (val) {
      return parseTime(val)
    },
    // delHtmlTag (str) {
    //   return str.replace(/<[^>]+>/g, '').replace(/&nbsp;/ig, '')
    // },
    // 点击预览
    async handleShow (id) {
      // console.log(id)
      // 打开弹层
      this.isShow = true
      // 获取点击对象的id发请求
      const { data } = await getQuestionsId(id)
      // 保存数据传递给子组件
      this.previewList = data
    },
    // 点击编辑
    async handleEdit (id) {
      await editQuestions(id)
      this.$router.push({ name: 'questions-new' })
    },
    // 点击删除
    handleDelete (id) {
      // 提示
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 发请求同步后台
        await delQuestions(id)
        // 发请求更新数据渲染视图
        this.getQuestionsList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 点击加入精选
    addChoice (id) {
      this.$confirm('此操作将该题目加入精选, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await addChoice(id, 1)
        this.getQuestionsList()
        this.$message({
          type: 'success',
          message: '已加入精选!'
        })
        this.$router.push({ name: 'questions-choice' })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    // pageSize 每页显示条目个数改变时会触发
    async handleSizeChange (val) {
      // console.log(val)
      // val 拿到的是当前选择的 条/页，会同时触发handleCurrentChange
      this.page.pagesize = val
      const { data } = await getQuestionsList({
        page: 1,
        pagesize: val
      })
      this.questionsList = data.items
      this.counts = data.counts
    },
    // currentPage 当前页数改变时会触发
    async handleCurrentChange (val) {
      // console.log(val)
      // val 拿到的是页数
      this.page.page = val
      const { data } = await getQuestionsList({
        page: val,
        pagesize: this.page.pagesize
      })
      this.questionsList = data.items
      this.counts = data.counts
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #fff;
  margin: 10px 0;
}
.topbtn {
  margin-bottom: 15px;
}
.explain {
  font-size: 12px;
  color: rgba(255, 192, 203);
}
.bottomBtn {
  text-align: right;
}
.selects{
  width: 100%;
}
.tableList{
  margin-top: 15px;
  margin-bottom: 25px;
}
.city{
  display: flex;
}
</style>
